<?php
namespace app\admin\controller;

use app\common\controller\AdminBaseController;
use think\facade\Config;
use think\Request;

/**
 *
 */
class SettingController extends AdminBaseController
{
    public function index()
    {
        // 调试模式
        $app = Config::pull('app');
        $data['app_debug'] = $app['app_debug'];
        $data['app_trace'] = $app['app_trace'];

        // 自定义系统参数
        $setting = Config::pull('setting');
        $setting = array_merge(['name' => '', 'website' => '', 'qq' => '', 'email' => '', 'phone' => ''], $setting);
        $data['name'] = $setting['name'];
        $data['website'] = $setting['website'];
        $data['qq'] = $setting['qq'];
        $data['email'] = $setting['email'];
        $data['phone'] = $setting['phone'];

        // 数据库
        $database = Config::pull('database');
        $data['hostname'] = $database['hostname'];
        $data['database'] = $database['database'];
        $data['username'] = $database['username'];
        $data['password'] = $database['password'];
        $data['prefix'] = $database['prefix'];
        $data['hostport'] = $database['hostport'];

        $this->assign($data);
        return $this->fetch();
    }

    // 生成配置文件
    public function save(Request $request)
    {
        self::testPost();

        $param = $request->param();

        if (isset($param['setting'])) {
            // 自定义内容保存到配置文件的 app.setting 里面
            $data = $param['setting'];
            //dump($data);
            if (admin_config_setting($data) === false) {
                $this->error('保存 setting.php 文件失败！');
            }
        }
        //$this->error('结束');

        if (isset($param['database'])) {
            // 生成.env文件
            $database = $param['database'];
            $app_debug = config('app_debug') ? 'true' : 'false';
            $app_trace = config('app_trace') ? 'true' : 'false';
            $app_debug = isset($param['app_debug']) ? $param['app_debug'] : $app_debug;
            $app_trace = isset($param['app_trace']) ? $param['app_trace'] : $app_trace;
            $data = [
                'app_debug' => $app_debug,
                'app_trace' => $app_trace,
                'hostname' => $database['hostname'],
                'database' => $database['database'],
                'username' => $database['username'],
                'password' => $database['password'],
                'hostport' => $database['hostport'],
                'prefix' => $database['prefix'],
            ];

            if (make_env($data) === false) {
                $this->error('保存 .env 文件失败！');
            }
        }

        // 返回成功信息
        $this->success('系统设置成功！', url('@admin/setting'), null, 1);

    }
}
